﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace CookieFreeAnalyticsDL
{
    public static class CFA_DL
    {
        //BlogEngine.Net d46077eb-61-411e-9fac-ae4df540b39a
        // Content page: page.aspx?id= {GUID}
        // Top level page: default.aspx?id= {GUID}
        // Post: post.aspx?id={GUID}

        //Immediacy
        // Page: ?page= INT


        // Datalayer class for looking up URLS from SQL database.
        // Was built to support Immediacy CMS. No longer required but left just in case
        public static string GetPageURL(string RequestUrlPathAndQuery)
        {
            string pageid;
            string sql;

             //Check for platform reference
             //If one is found load settings for database access
            if (CookieFreeAnalytics.CFAGlobal.EnableSQL)
            {
                 //Check we are on a page with relevant ID
                if (HttpContext.Current.Request.QueryString[CookieFreeAnalytics.CFAGlobal.platformQueryStringKey] != null)
                {
                     //Here we need to extract rest of the query string parameters to put on the end of the url
                     //Otherwise utm campaign codes would go missing

                    string fullquery;

                    try
                    {
                        pageid = HttpContext.Current.Request.QueryString[CookieFreeAnalytics.CFAGlobal.platformQueryStringKey];
                        // If we are expecting a GUID, check its a valid format
                        if (CookieFreeAnalytics.CFAGlobal.platformQueryStringKeyFormat.Equals("guid"))
                        {
                            Guid safeGUID;
                            if (TryStrToGuid(pageid, out safeGUID))
                            {
                                pageid = safeGUID.ToString();
                            }
                            else
                            {
                                return HttpUtility.UrlEncode(RequestUrlPathAndQuery + "&ex=2");
                            }
                        }
                        if (CookieFreeAnalytics.CFAGlobal.platformQueryStringKeyFormat.Equals("int"))
                        {
                            int safeInt;
                            if (TryStrToInt(pageid, out safeInt))
                            {
                                pageid = safeInt.ToString();
                            }
                            else
                            {
                                return HttpUtility.UrlEncode(RequestUrlPathAndQuery + "&ex=2");
                            }
                        }
                        

                        fullquery = FixQueryString(HttpContext.Current.Request.QueryString.ToString(), CookieFreeAnalytics.CFAGlobal.platformQueryStringKey, pageid);
                        SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CookieFreeAnalyticsConnectionString"].ToString());
                        conn.Open();
                        sql = "select " + CookieFreeAnalytics.CFAGlobal.URLField + " from " + CookieFreeAnalytics.CFAGlobal.tableName + " where " + CookieFreeAnalytics.CFAGlobal.IDfield + "='" + pageid + "'";
                        if (CookieFreeAnalytics.CFAGlobal.OrderByField.Length > 0)
                        {
                            sql = sql + " Order by " + CookieFreeAnalytics.CFAGlobal.OrderByField + " desc";
                        }
                        SqlCommand sqlcom = new SqlCommand(sql, conn);
                        string platformURL = sqlcom.ExecuteScalar().ToString();
                        return HttpUtility.UrlEncode(platformURL + fullquery);
                    }
                    catch (Exception)
                    {
                        return HttpUtility.UrlEncode(RequestUrlPathAndQuery + "&ex=1");
                    }
                }

                //CookieFreeAnalytics.CFA_Core.ResponseDebug("#p2#" + HttpUtility.UrlEncode(RequestUrlPathAndQuery));
                if (RequestUrlPathAndQuery.ToLower().Equals("/default.aspx"))
                {
                    return HttpUtility.UrlEncode("/");
                }
            }

             //Back up plan
            return HttpUtility.UrlEncode(RequestUrlPathAndQuery);

        }


         //Check to see if GUID is valid
        public static Boolean TryStrToGuid(String s, out Guid value)
        {

            // this is before the overhead of setting up the try/catch block.
            if (s == null || s.Length < 32 || s.Length > 38)
            {
                value = Guid.Empty;
                return false;
            }

            try
            {
                value = new Guid(s);
                return true;
            }
            catch (FormatException)
            {
                value = Guid.Empty;
                return false;
            }
        }

         //Check to see if INT is valid
        public static Boolean TryStrToInt(String s, out int value)
        {
            bool result = int.TryParse(s, out value);
            return result;
        }

        public static string FixQueryString(string fullquery, string pageidkey, string pageidvalue)
        {
             //Extract the part of the querystring with pageidkey (page) the = and the page number

            string temp = "";

            temp = fullquery.Replace(pageidkey + "=" + pageidvalue, "");
            if (temp.IndexOf("&").Equals(0))
            {
                 //We need to remove the first & and replace with "?"
                return "?" + temp.Substring(1);
            }

            return temp;
        }

        // //Replaced with CFAGlobal app settings cache
        //public static bool LoadSettings()
        //{
        //    //bool successFullLoad = true;

        //    //// Querystring key. Usually ?ID= or ?page=
        //    //if (System.Configuration.ConfigurationManager.AppSettings["CookieFreePlatformQueryStringKey"] != null)
        //    //{
        //    //    platformQueryStringKey = System.Configuration.ConfigurationManager.AppSettings["CookieFreePlatformQueryStringKey"].ToString();
        //    //}
        //    //else
        //    //{
        //    //    successFullLoad = false;
        //    //}

        //    //// Database Table Name
        //    //if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeTableName"] != null)
        //    //{
        //    //    tableName = System.Configuration.ConfigurationManager.AppSettings["CookieFreeTableName"].ToString();
        //    //}
        //    //else
        //    //{
        //    //    successFullLoad = false;
        //    //}

        //    //// Fieldname for page ID
        //    //if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeIDFieldName"] != null)
        //    //{
        //    //    IDfield = System.Configuration.ConfigurationManager.AppSettings["CookieFreeIDFieldName"].ToString();
        //    //}
        //    //else
        //    //{
        //    //    successFullLoad = false;
        //    //}

        //    //// Fieldname for page url
        //    //if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeURLFieldName"] != null)
        //    //{
        //    //    URLField = System.Configuration.ConfigurationManager.AppSettings["CookieFreeURLFieldName"].ToString();
        //    //}
        //    //else
        //    //{
        //    //    successFullLoad = false;
        //    //}

        //    //// Fieldname for ordering date created. Incase of multiple urls
        //    //if (System.Configuration.ConfigurationManager.AppSettings["CookieFreeOrderByFieldName"] != null)
        //    //{
        //    //    OrderByField = System.Configuration.ConfigurationManager.AppSettings["CookieFreeOrderByFieldName"].ToString();
        //    //}
        //    //else
        //    //{
        //    //    successFullLoad = false;
        //    //}

        //    return successFullLoad;
        //}

    }
}